package com.fanghaoran.notes.filter;

import com.alibaba.fastjson.JSON;
import com.fanghaoran.notes.bean.MyResult;
import com.fanghaoran.notes.entity.User;
import com.fanghaoran.notes.util.Constants;
import jakarta.servlet.*;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: win11
 * @Date: 2023/04/28/20:02
 * @Description: 登录过滤器
 */

public class LoginCheckFilter implements Filter {

    /**
     * 不经过过滤器的方法以及静态页面
     */
    private List<String> excludeUrls;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludeUrlStr = filterConfig.getInitParameter("excludeUrls");
        //把排除路径放到集合
        excludeUrls= Arrays.asList(excludeUrlStr.split(","));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        //1.获取请求url及参数
        String url = request.getRequestURL().toString();
        String method = request.getParameter(Constants.METHOD);

        //2.判断是否是登录操作 如果是就放行
        if(excludeUrls.contains(method) ||url.contains(Constants.HTML)||url.contains(Constants.CSS)||url.contains(Constants.JS)
                ||url.contains(Constants.IMAGE)||url.contains(Constants.FONT)){
            chain.doFilter(request,response);
            return;
        }

        //3.获取session或者cookie
        User user = (User) request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        //获取浏览器cookie
        Cookie[] cookies = request.getCookies();
        int uId = 0;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //找自动登录的cookie
                if (cookie.getName().equals(Constants.AUTO_USER_PARAM)) {
                    uId =Integer.parseInt(cookie.getValue()) ;
                    break;
                }
            }
        }
        //已登录
        if (user != null || uId!=0) {
            if(request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM)==null){
                User user1=new User();
                user1.setUId(uId);
                request.getSession().setAttribute(Constants.LOGIN_SESSION_PARAM, user1);
            }
            chain.doFilter(request,response);
        }else{
            //未登录
            response.getWriter().println(JSON.toJSONString(new MyResult(Constants.UN_LOGIN,"未登录")));
        }
    }
}
